import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:hao/utils/RecordModel.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sprintf/sprintf.dart';
import 'package:timezone/timezone.dart' as tz;

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

class AddRecordViewModel extends GetxController {
  final TextEditingController titleController = TextEditingController();
  final TextEditingController priceController = TextEditingController();
  final TextEditingController remarkController = TextEditingController();

  final timeStr = "".obs;
  final expireStr = "".obs;
  final isRemind = false.obs;

  // final Hao? chu;
  final Record? chu;

  AddRecordViewModel({this.chu});

  @override
  void onInit() {
    super.onInit();
    configTime(false, DateTime.now(), TimeOfDay.now());
    configTime(
        true, DateTime.now().add(const Duration(days: 1)), TimeOfDay.now());

    if (chu != null) {
      titleController.text = chu?.title ?? "";
      priceController.text = chu?.price ?? "";
      remarkController.text = chu?.remark ?? "";
      timeStr.value = chu?.time ?? "";
      expireStr.value = chu?.expire ?? "";
      isRemind.value = chu?.isRemind ?? false;
    }
  }

  void changeRemind(bool isRemind) {
    if (isRemind) {
      flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
            alert: true,
            badge: true,
            sound: true,
          )
          .then((value) {
        if (value != null) {
          if (value) {
            this.isRemind.value = isRemind;
          } else {
            Fluttertoast.showToast(msg: "请开启推送开关");
          }
        }
      });
    } else {
      this.isRemind.value = isRemind;
    }
  }

  Future<void> _showNotification(int id) async {
    const iosPlatformChannelSpecifics = IOSNotificationDetails();
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(iOS: iosPlatformChannelSpecifics);

    DateTime dateTime = DateTime.parse(expireStr.value);

    await flutterLocalNotificationsPlugin.zonedSchedule(
      id,
      '账号租管家',
      '${titleController.text} 到期了',
      tz.TZDateTime.from(dateTime, tz.local),
      platformChannelSpecifics,
      androidAllowWhileIdle: false,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
    );
  }

  void chooseTime(bool isExpire) {
    showDatePicker(
      context: Get.context!,
      initialDate: isExpire
          ? DateTime.now().add(const Duration(days: 1))
          : DateTime.now(),
      firstDate: DateTime(2022),
      lastDate: DateTime(2023),
    ).then((value) {
      if (value != null) {
        showTimePicker(initialTime: TimeOfDay.now(), context: Get.context!)
            .then((time) {
          if (time != null) {
            configTime(isExpire, value, time);
          }
        });
      }
    });
  }

  void configTime(bool isExpire, DateTime dateTime, TimeOfDay timeOfDay) {
    String str = sprintf("%04d-%02d-%02d %02d:%02d", [
      dateTime.year,
      dateTime.month,
      dateTime.day,
      timeOfDay.hour,
      timeOfDay.minute
    ]);
    if (isExpire) {
      expireStr.value = str;
    } else {
      timeStr.value = str;
    }
  }

  void addRecord() async {
    String title = titleController.text;
    String price = priceController.text;
    String remark = remarkController.text;

    if (title.isEmpty) {
      Fluttertoast.showToast(msg: "请输入租用物品");
      return;
    }

    if (price.isEmpty) {
      Fluttertoast.showToast(msg: "请输入金额");
      return;
    }

    DateTime startTime = DateTime.parse(timeStr.value);
    DateTime endTime = DateTime.parse(expireStr.value);
    if (endTime.isBefore(startTime)) {
      Fluttertoast.showToast(msg: "开始时间不能大于结束时间");
      return;
    }

    DateTime dateTime = DateTime.now();

    if (chu != null) {
      chu!.title = title;
      chu!.price = price;
      chu!.time = timeStr.value;
      chu!.remark = remark;
      chu!.expire = expireStr.value;
      chu!.isRemind = isRemind.value;

      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      String str = sharedPreferences.getString("list") ?? "[]";
      List _list = json.decode(str);
      for (int i = 0; i < _list.length; i ++) {
        Map map = _list[i];
        int id = map["id"];
        if (id == chu!.id) {
          _list[i] = chu!.toJson();
          break;
        }
      }

      sharedPreferences.setString("list", json.encode(_list)).then((value){
        Get.back(result: true);
      });

      // chu!.update().then((value) {
      //   Get.back(result: true);
      // });

      if (isRemind.value) {
        _showNotification(chu?.id ?? 1);
      } else {
        flutterLocalNotificationsPlugin.cancel(chu?.id ?? 1);
      }
    } else {
      int id = (dateTime.millisecondsSinceEpoch / 1000.0).floor();
      Record chu = Record(
          id: id,
          title: title,
          price: price,
          time: timeStr.value,
          expire: expireStr.value,
          isRemind: isRemind.value,
          remark: remark);

      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      String str = sharedPreferences.getString("list") ?? "[]";
      List _list = json.decode(str);
      _list.add(chu);

      sharedPreferences.setString("list", json.encode(_list)).then((value){
          Get.back(result: true);
      });

      if (isRemind.value) {
        _showNotification(id);
      }
    }
  }
}
